<template>
  <el-dialog
    class="basic-dialog"
    :model-value="visible"
    title="加入分组"
    :width="400"
    top="30vh"
    :close-on-click-modal="!loading"
    :close-on-press-escape="!loading"
    :show-close="!loading"
    @closed="handleClosed"
    @open="handleDialogOpen"
  >
    <el-form
      ref="formRef"
      :model="formData"
      :rules="rules"
      label-position="top"
      require-asterisk-position="right"
      @submit.prevent
    >
      <el-form-item required label="选择分组" prop="group">
        <el-select
          v-model="formData.group"
          class="w-full"
          placeholder="请选择分组"
          remote
          filterable
          :loading="groupLoading"
          remote-show-suffix
          fit-input-width
          :remote-method="remoteMethod"
        >
          <el-option
            v-for="item in groupList"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          >
            <text-ell :content="item.label" />
          </el-option>
        </el-select>
      </el-form-item>
    </el-form>

    <template #footer>
      <el-button
        :loading="loading"
        type="primary"
        :disabled="!formData.group"
        @click="handleSubmit"
      >
        确定
      </el-button>
      <el-button :loading="loading" @click="emit('update:visible', false)"
        >取消</el-button
      >
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import type { FormInstance, FormItemRule } from 'element-plus'
import type { Ref } from 'vue'

import type { DomainModel } from '@/apis/model/domain'
import type { UserModel } from '@/apis/model/user'
import { useSelectRemote } from '@/hooks/useSelectRemote'
import ToastUtils from '@/utils/toast'

interface IProps {
  visible: boolean
  loading?: boolean
}

interface IEmits {
  (event: 'update:visible', value: boolean): void
  (event: 'update:loading', value: boolean): void
  (event: 'reload'): void
}

const rules: Record<string, FormItemRule[]> = {
  group: [{ required: true, message: '请选择分组', trigger: 'change' }]
}

const emit = defineEmits<IEmits>()
const props = defineProps<IProps>()

const selectedRows = inject('selectedRows') as Ref<DomainModel[]>
const user = inject('user') as Ref<UserModel | undefined>

const formRef = ref<FormInstance>()
const formData = reactive({
  group: ''
})

/**
 * 分组列表
 */
const {
  remoteMethod,
  opts: groupList,
  loading: groupLoading
} = useSelectRemote(user.value ? userDomainGroupListApi : domainGroupListApi, {
  valueKey: 'id',
  labelKey: 'name',
  queryKey: 'name',
  defaultState: {
    user_id: user.value?.id
  }
})

remoteMethod('')

watch(
  () => props.visible,
  () => {
    remoteMethod('')
  }
)

/**
 * 保存方法
 */
const handleSubmit = async () => {
  await formRef.value?.validate()
  emit('update:loading', true)
  try {
    const ids = selectedRows.value.map(item => item.id) as string[]
    const fn = user.value ? joinUserDomainGroupApi : joinDomainGroupApi
    await fn({
      id: formData.group,
      domain_ids: ids
    })
    ToastUtils.success('添加成功')
    emit('update:visible', false)
    emit('reload')
  } finally {
    emit('update:loading', false)
  }
}

/**
 * @description dialog 打开事件
 */
const handleDialogOpen = () => {}

/**
 * @description dialog 关闭前事件
 */
const handleClosed = () => {
  formRef.value?.resetFields()
  emit('update:visible', false)
  emit('update:loading', false)
}
</script>

<style scoped></style>
